package com.ideyatech.errorhandling.dao.jpa;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.ideyatech.errorhandling.dao.BaseDao;

public class BaseDaoJpaSupport<T> extends JpaDaoSupport implements BaseDao<T> {

    private Class<T> entityBeanType;

    @SuppressWarnings("unchecked")
    public BaseDaoJpaSupport() {
	ParameterizedType genericSuperclass = (ParameterizedType) getClass()
		.getGenericSuperclass();
	entityBeanType = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }

    @Override
    public T load(Long id) {
	return getJpaTemplate().find(entityBeanType, id);
    }

    @Override
    public void saveEntity(T entity) {
	getJpaTemplate().persist(entity);
    }

    @Override
    public void mergeEntity(T entity) {
	getJpaTemplate().merge(entity);
    }

    @Override
    public void deleteEntity(Long id) {
	T entity = getJpaTemplate().find(entityBeanType, id);
	getJpaTemplate().remove(entity);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll() {
	String jpql = "from " + entityBeanType.getName() + " obj";
	return getJpaTemplate().find(jpql);
    }

    @SuppressWarnings("unchecked")
    protected T getSingleResultEntityByNamedQuery(String strQuery,
	    Map<String, Object> params) {
	return (T) DataAccessUtils.singleResult(getJpaTemplate()
		.findByNamedParams(strQuery, params));
    }
    
    @SuppressWarnings("unchecked")
    protected List<T> getEntityListByNamedQuery(String strQuery, Map<String, Object> params) {
	return getJpaTemplate().findByNamedParams(strQuery, params);
    }

}
